<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改采购')"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-purchase-edit" th:object="${chainPurchase}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">合作公司：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input id="cooperationId" name="cooperationId" type="hidden" th:value="*{cooperationId}"/>
                    <input type="hidden" id="wholesalePrice" th:value="${wholesalePrice}">
                    <input type="hidden" id="cooCommodityQuantity" th:value="${cooCommodityQuantity}">
                    <input class="form-control" disabled type="text" onclick="selectCooperationIdRadio()"
                           id="cooperationName"
                           readonly="true" th:value="*{cooperationName}" required>
                    <span class="input-group-addon"><i class="fa fa-search"></i></span>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label is-required">商品名称：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input id="cooCommodityId" name="cooCommodityId" type="hidden" th:value="*{cooCommodityId}"/>
                    <input class="form-control" disabled type="text" onclick="selectCommodityIdRadio()"
                           id="commodityName"
                           readonly="true" th:value="*{commodityName}" required>
                    <span class="input-group-addon"><i class="fa fa-search"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">采购人：</label>
            <div class="col-sm-8">
                <div class="input-group">
                    <input id="userId" name="userId" type="hidden" th:value="*{userId}"/>
                    <input class="form-control" type="text" onclick="selectUserIdRadio()" id="userName"
                           readonly="true" th:value="*{userName}" required>
                    <span class="input-group-addon"><i class="fa fa-search"></i></span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">商品图片：</label>
            <div class="col-sm-8">
                <img th:src="*{image}" width="150" height="100">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">数量：</label>
            <div class="col-sm-8">
                <input name="quantity" th:field="*{quantity}" class="form-control" type="text" required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">金额：</label>
            <div class="col-sm-8">
                <input name="amount" th:field="*{amount}" class="form-control" type="text" readonly required>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">运输方式：</label>
            <div class="col-sm-8">
                <select name="transportType" class="form-control m-b" th:with="type=${@dict.getType('transport_type')}"
                        required>
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                            th:field="*{transportType}"></option>
                </select>
            </div>
        </div>
        <div class="hr-line-dashed"></div>
        <div class="form-group">
            <label class="col-sm-3 control-label">审核意见：</label>
            <div class="col-sm-8">
                <textarea id="auditInfo" disabled name="auditInfo" th:text="*{auditInfo}"
                          class="form-control"></textarea>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var prefix = ctx + "chain/purchase";
    var cooperationPrefix = ctx + "chain/cooperation"
    var commodityPrefix = ctx + "chain/commodity";
    var userPrefix = ctx + "system/user";
    $("#form-purchase-edit").validate({
        focusCleanup: true
    });

    $(function() {
        // 数量输入实时监听
        $("#quantity").on('input propertychange', function() {
            calculateAmount();
            checkInventory();
        });
    });

    // 金额计算函数
    function calculateAmount() {
        // 获取采购数量
        let quantity = parseFloat($("#quantity").val().trim()) || 0;
        // 获取采购单价
        let price = parseFloat($("#wholesalePrice").val().trim()) || 0;

        // 清空错误数据
        $("#amount").val('');

        // 输入有效性校验
        if ($("#quantity").val().trim() === "") return;

        if (isNaN(price) || price <= 0) {
            if (quantity > 0) {
                $.modal.alertWarning('请选择有效的商品');
            }
            return;
        }

        if (isNaN(quantity) || quantity <= 0) {
            if ($("#quantity").val().length > 0) {
                $.modal.alertWarning('请输入有效的采购数量');
            }
            return;
        }

        // 计算并保留两位小数
        $("#amount").val((quantity * price).toFixed(2));
    }

    // 库存检查函数
    function checkInventory() {
        // 获取用户输入的采购数量（ChainPurchase.quantity）
        const quantity = parseInt($("#quantity").val()) || 0;
        // 获取合作商品库存量（ChainCooperationCommodity.quantity）
        const stockQty = parseInt($("#cooCommodityQuantity").val()) || 0;

        // 校验采购数量是否超过库存
        if (quantity > stockQty) {
            $.modal.alertWarning(`库存不足！最大可用数量：${stockQty}`);
            $("#quantity").val(Math.max(stockQty,0)).trigger('input');
        }
    }

    function selectCooperationIdRadio() {
        var options = {
            title: '选择合作公司',
            url: cooperationPrefix + "/selectCooperation",
            callBack: doCooperationSubmit
        };
        $.modal.openOptions(options);
    }

    function selectUserIdRadio() {
        var options = {
            title: '选择商品库存',
            url: userPrefix + "/selectUser?deptId=103",
            callBack: doUserSubmit
        };
        $.modal.openOptions(options);
    }


    function selectCommodityIdRadio() {
        var options = {
            title: '选择商品',
            url: commodityPrefix + "/selectCommodity",
            callBack: doCommoditySubmit
        };
        $.modal.openOptions(options);
    }

    function doUserSubmit(index, layer) {
        var body = $.modal.getChildFrame(index);
        $("#userId").val(body.find("#userId").val());
        $("#userName").val(body.find("#userName").val());
        $.modal.close(index);
    }

    function doCooperationSubmit(index, layer) {
        const body = $.modal.getChildFrame(index);
        const data = {
            cooCommodityId: body.find("#id").val(),
            wholesalePrice: body.find("#wholesalePrice").val(),
            cooCommodityQuantity: body.find("#cooCommodityQuantity").val(),
            commodityName: body.find("#commodityName").val()
        };
        // 数据绑定
        $("#cooCommodityId").val(data.cooCommodityId);
        $("#wholesalePrice").val(data.wholesalePrice);
        $("#cooCommodityQuantity").val(data.quantity);
        $("#commodityName").val(data.commodityName);

        $("#quantity").trigger('input');
        $.modal.close(index);
    }


    function doCommoditySubmit(index, layer) {
        const body = $.modal.getChildFrame(index);
        const commodityData = {
            id: body.find("#cooCommodityId").val(),
            name: body.find("#commodityName").val(),
            price: body.find("#wholesalePrice").val(),  // 使用实际价格字段
            stock: body.find("#cooCommodityQuantity").val()  // 使用实际库存字段
        };

        $("#cooCommodityId").val(commodityData.id);
        $("#wholesalePrice").val(commodityData.price);
        $("#cooCommodityQuantity").val(commodityData.stock);

        // 初始化金额计算
        $("#quantity").trigger('input');
        $.modal.close(index);
    }


    function submitHandler() {
        if (!$("#form-purchase-edit").valid()) return;

        // 最终库存校验
        const quantity = parseInt($("#quantity").val());
        const stock = parseInt($("#cooCommodityQuantity").val());

        if (quantity > stock) {
            $.modal.alertWarning("当前库存不足，请调整采购数量");
            return;
        }

        $.operate.save(prefix + "/edit", $('#form-purchase-edit').serialize());
    }

</script>
</body>
</html>